<?php

    /**
    * This is the model class for table "post_reply".
    *
    * The followings are the available columns in table 'post_reply':
    * @property string $id
    * @property string $post_id
    * @property string $content
    * @property string $cat_parent_id
    * @property string $cat_id
    * @property string $user_id
    * @property string $parent_id
    * @property string $reply_id
    * @property string $created
    * @property string $changed
    *
    * The followings are the available model relations:
    * @property PostImage[] $postImages
    * @property PostReply $reply
    * @property PostReply[] $postReplies
    * @property Post $post
    * @property PostReply $parent
    * @property PostReply[] $postReplies1
    * @property UserFollowUserAction[] $userFollowUserActions
    * @property UserLikeReply[] $userLikeReplies
    * @property User $user
    */
    class PostReply extends CActiveRecord
    {
        /**
        * @return string the associated database table name
        */

        public $childs = array();
        public function tableName()
        {
            return 'post_reply';
        }

        /**
        * @return array validation rules for model attributes.
        */
        public function rules()
        {
            // NOTE: you should only define rules for those attributes that
            // will receive user inputs.
            return array(
                array('content', 'required', 'message' => 'Nội dung trả lời không được bỏ trống'),
                array('cat_parent_id, cat_id, post_id, user_id, created', 'required'),               
                array('post_id, parent_id, reply_id', 'length', 'max'=>10),
                array('content', 'length', 'min'=>20, 'message' => 'Nội dung trả lời phải từ 20 ký tự trở lên'),
                array('desc', 'length', 'max'=>500),
                array('changed', 'safe'),
                // The following rule is used by search().
                // @todo Please remove those attributes that should not be searched.
                array('id, post_id, content, user_id, parent_id, reply_id, created, changed', 'safe', 'on'=>'search'),
            );
        }

        /**
        * @return array relational rules.
        */
        public function relations()
        {
            // NOTE: you may need to adjust the relation name and the related
            // class name for the relations automatically generated below.
            return array(
                'postImages' => array(self::HAS_MANY, 'PostImage', 'reply_id'),
                'post' => array(self::BELONGS_TO, 'Post', 'post_id'),

                'postReplyReply' => array(self::BELONGS_TO, 'PostReply', 'reply_id'),
                'postReplyParent' => array(self::BELONGS_TO, 'PostReply', 'parent_id'),

                'postRepliesByReply' => array(self::HAS_MANY, 'PostReply', 'reply_id'),
                'postRepliesByParent' => array(self::HAS_MANY, 'PostReply', 'parent_id'),

                'userFollowUserActions' => array(self::HAS_MANY, 'UserFollowUserAction', 'reply_id'),
                'userLikeReplies' => array(self::HAS_MANY, 'UserLikeReply', 'reply_id'),
                'user' => array(self::BELONGS_TO, 'User', 'user_id'),
            );
        }

        /**
        * @return array customized attribute labels (name=>label)
        */
        public function attributeLabels()
        {
            return array(
                'id' => 'ID',
                'post_id' => 'Post',
                'content' => 'Content',
                'user_id' => 'User',
                'parent_id' => 'Parent',
                'reply_id' => 'Reply',
                'created' => 'Created',
                'changed' => 'Changed',
            );
        }

        /**
        * Retrieves a list of models based on the current search/filter conditions.
        *
        * Typical usecase:
        * - Initialize the model fields with values from filter form.
        * - Execute this method to get CActiveDataProvider instance which will filter
        * models according to data in model fields.
        * - Pass data provider to CGridView, CListView or any similar widget.
        *
        * @return CActiveDataProvider the data provider that can return the models
        * based on the search/filter conditions.
        */
        public function search()
        {
            // @todo Please modify the following code to remove attributes that should not be searched.

            $criteria=new CDbCriteria;

            $criteria->compare('id',$this->id,true);
            $criteria->compare('post_id',$this->post_id,true);
            $criteria->compare('content',$this->content,true);
            $criteria->compare('user_id',$this->user_id,true);
            $criteria->compare('parent_id',$this->parent_id,true);
            $criteria->compare('reply_id',$this->reply_id,true);
            $criteria->compare('created',$this->created,true);
            $criteria->compare('changed',$this->changed,true);

            return new CActiveDataProvider($this, array(
                'criteria'=>$criteria,
            ));
        }

        /**
        * Returns the static model of the specified AR class.
        * Please note that you should have this exact method in all your CActiveRecord descendants!
        * @param string $className active record class name.
        * @return PostReply the static model class
        */
        public static function model($className=__CLASS__)
        {
            return parent::model($className);
        }
        
        public function filterAttributes(){
            $purifier=new CHtmlPurifier();
            $purifier->options = array(
                //                'HTML.AllowedAttributes' => 'a.rel, a.href, a.target, img.src, *.title, *.style',
                'Attr.AllowedRel' => array('nofollow'),
                'HTML.TargetBlank' => true,
            ); 
            $this->content = strip_tags($this->content, '<strong><em><u><del><p><br><div><span><a><img><ul><o><li>');
            $this->content = $purifier->purify($this->content);    
            $this->content = preg_replace(array(
                '{[\n\s]+}', 
                '{(\s*(<\s*br\s*/?\s*>)\s*){3,}}'
                ), array(
                    ' ',
                    '<br /><br />'
                ), $this->content);

            $rows = explode('<br />', $this->content);
            $rows2 = array();
            foreach($rows as $row){
                //http://www.asciitable.com/
                //echo '<pre>';print_r(ord($row));echo '</pre>';
                if(ord($row) < 176)  
                    $rows2[] = trim($row);
            }
            $this->content = implode("\n", $rows2);
            $this->content = trim($this->content);
            $this->content = str_replace("\n", '<br />', $this->content);

            $this->desc = Myext::char_limiter(strip_tags($this->content, '<br>'), 200);
            $this->desc = preg_replace('{(\s*(<\s*br\s*/?\s*>)\s*){3,}}', '<br /><br />', $this->desc);
        }
        
        
        public function beforeSave(){
            return parent::beforeSave();
        }
        
        public function afterSave(){
            return parent::afterSave();
        }

        public function afterDelete(){
            return parent::afterSave();
        }
        
        public function getModel($id, $condition=''){
            $model = $this->findByPk($id, $condition);
            if(!$model) throw new CHttpException(404, 'Bài trả lời không tồn tại');
            return $model;
        }
        
        public function checkUserPermisstion($replyId = null){
            $user = Yii::app()->user->user;
            if(!$user) return false;
            
            $userInfo = Yii::app()->user->userInfo;
            if($userInfo && $userInfo->isMod) return true;

            $replyId = $replyId ? $replyId : $this->id;
            return PostReply::model()->exists('id = :id AND user_id = :user_id', array(':id' => $replyId, ':user_id' => $user->id));
        }
        
        public function getImagePath($id = null, $post_id = null){
            $id = $id ? $id : $this->id;
            $post_id = $post_id ? $post_id : $this->post_id;
            $postPath = Post::model()->getImagePath($post_id);
            return "{$postPath}/{$id}/"; 
        } 
        
        public function deleteFiles(){
            Myext::deleteDir($this->getImagePath());       
        } 
    }
